import type {
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
} from '@fast-crud/fast-crud';

import type { Recordable } from '@vben/types';

import { ref, unref } from 'vue';

import { dict } from '@fast-crud/fast-crud';
import { split, uniqueId } from 'lodash-es';

import { findOnlineService, findSystemApi } from '#/api';

const { VITE_GLOB_MODE } = import.meta.env;
export function createCrudOptions(
  props: CreateCrudOptionsProps,
): CreateCrudOptionsRet {
  const apiMap = ref<Recordable>({}); // 后端返回集合

  // 获取已经选中的uri
  function getSelectedOptions(controller: string) {
    const selectedOptions: string[] = [];
    const selectedData = props.context.selectedData;
    // 已选列表
    for (const selected of selectedData) {
      // 后台返回的所有的uri
      for (const uri of unref(apiMap)[controller]) {
        if (
          selected.springApplicationName === uri.springApplicationName &&
          selected.uri === uri.uri &&
          selected.requestMethod === uri.requestMethod
        ) {
          selectedOptions.push(
            `${uri.springApplicationName}#${uri.controller}#${uri.uri}#${uri.requestMethod}#${uri.name}`,
          );
        }
      }
    }
    return selectedOptions;
  }

  function delSelectedData(obj: Recordable) {
    const selectedData = props.context.selectedData;
    const index = selectedData.findIndex(
      (selected: any) =>
        selected.springApplicationName === obj.springApplicationName &&
        selected.uri === obj.uri &&
        selected.requestMethod === obj.requestMethod,
    );

    if (index !== -1) {
      selectedData.splice(index, 1);
    }
  }

  function addSelectedData(obj: Recordable) {
    let flag = false;
    const selectedData = props.context.selectedData;
    for (const selected of selectedData) {
      if (
        selected.springApplicationName === obj.springApplicationName &&
        selected.uri === obj.uri &&
        selected.requestMethod === obj.requestMethod
      ) {
        flag = true;
        break;
      }
    }
    if (!flag) {
      selectedData.push(obj);
    }
  }

  return {
    crudOptions: {
      form: { mode: 'add', col: { span: 24 } },
      columns: {
        service: {
          title: '服务名',
          type: 'dict-select',
          dict: dict({
            async getData() {
              return await findOnlineService();
            },
          }),
          form: {
            component: { showSearch: true },
            helper: {
              position: 'label',
              text: 'lamp-cloud: 自动查询后台已经正常启动并注册到nacos中的服务 \nlamp-boot: 后台拆分的模块',
            },
            async valueChange({ value, getComponentRef, form }) {
              apiMap.value = await findSystemApi(value);

              const controllerOptions: Recordable[] = [];
              for (const controller in unref(apiMap)) {
                controllerOptions.push({
                  value: controller,
                  key: controller,
                  label: controller,
                });
              }

              const controllerRef = getComponentRef('controller');
              const dictRef = controllerRef.getDict();
              dictRef.data = controllerOptions;
              form.controller = undefined;
              form.uri = undefined;
            },
          },
        },
        controller: {
          title: '控制器类名',
          dict: dict({ data: [] }),
          type: 'dict-select',
          form: {
            component: { showSearch: true },
            async valueChange({ value, getComponentRef, form }) {
              const uriOptions: Recordable[] = [];
              for (const controller in unref(apiMap)) {
                if (controller === value) {
                  const map = unref(apiMap);
                  const uriList = map[controller];
                  for (const uri of uriList) {
                    const uriStr =
                      VITE_GLOB_MODE === 'boot'
                        ? `/${form.service}${uri.uri}`
                        : `${uri.uri}`;

                    uriOptions.push({
                      value: `${uri.springApplicationName}#${uri.controller}#${uriStr}#${uri.requestMethod}#${uri.name}`,
                      key:
                        uri.springApplicationName + uriStr + uri.requestMethod,
                      label: `${uriStr}【${uri.requestMethod}】(${uri.name})`,
                    });
                  }
                }
              }

              const uriRef = getComponentRef('uri');
              const dictRef = uriRef.getDict();
              dictRef.data = uriOptions;

              form.uri = getSelectedOptions(value);
            },
          },
        },
        uri: {
          title: '接口地址',
          dict: dict({ data: [] }),
          type: 'dict-select',
          form: {
            component: { showSearch: true, mode: 'multiple' },
            async valueChange(context) {
              const { value, getComponentRef, form } = context;
              const dictRef = getComponentRef('uri').getDict();
              const uriOptions = dictRef.data;

              // 先删除
              for (const uri of uriOptions) {
                const valueList = split(uri.value, '#');
                delSelectedData({
                  springApplicationName: valueList[0],
                  uri: valueList[2],
                  requestMethod: valueList[3],
                });
              }

              // 在选择
              if (value && value.length > 0) {
                for (const item of value) {
                  const valueList = split(item, '#');
                  addSelectedData({
                    springApplicationName: valueList[0],
                    controller: valueList[1],
                    uri: valueList[2],
                    requestMethod: valueList[3],
                    name: valueList[4],
                    isInput: false,
                    tempId: uniqueId(),
                  });
                }
              } else {
                // 取消了所有
                const apiList = apiMap.value[form.controller];
                for (const api of apiList) {
                  delSelectedData(api);
                }
              }
            },
          },
        },
      },
    },
  };
}
